/**
 * 分类详情页面交互逻辑
 */
import { fetchDataById, deleteDataItem } from '../../js/api.js';

/**
 * 从URL获取分类ID
 */
function getCategoryIdFromUrl() {
    const params = new URLSearchParams(window.location.search);
    const id = params.get('id');
    return id ? parseInt(id) : null;
}

/**
 * 渲染分类详情数据
 * @param {Object} data - 分类详情数据
 */
function renderCategoryDetail(data) {
    document.getElementById('categoryId').textContent = data.id;
    document.getElementById('categoryName').textContent = data.name;
    document.getElementById('categoryParentId').textContent = data.parent_id || '-';
    document.getElementById('categoryDescription').textContent = data.description || '-';
    document.getElementById('categoryCreatedAt').textContent = new Date(data.created_at).toLocaleString();
    document.getElementById('categoryUpdatedAt').textContent = new Date(data.updated_at).toLocaleString();
}

/**
 * 加载分类详情数据
 */
async function loadCategoryDetail() {
    const id = getCategoryIdFromUrl();
    if (!id) {
        alert('无效的分类ID');
        window.location.href = 'list.html';
        return;
    }

    try {
        const data = await fetchDataById(id);
        renderCategoryDetail(data);
    } catch (error) {
        console.error('加载分类详情失败:', error);
        alert('加载分类详情失败: ' + (error.message || '未知错误'));
    }
}

/**
 * 初始化删除按钮事件
 */
function initDeleteButton() {
    const deleteBtn = document.getElementById('deleteBtn');
    deleteBtn.addEventListener('click', async () => {
        const id = getCategoryIdFromUrl();
        if (!id) return;

        if (confirm('确定要删除此分类吗？此操作不可撤销！')) {
            try {
                const success = await deleteDataItem(id);
                if (success) {
                    alert('分类删除成功！');
                    window.location.href = 'list.html';
                }
            } catch (error) {
                console.error('删除分类失败:', error);
                alert('删除分类失败: ' + (error.message || '未知错误'));
            }
        }
    });
}

// 页面加载完成后初始化
window.addEventListener('DOMContentLoaded', () => {
    loadCategoryDetail();
    initDeleteButton();
});